<template>
	<div class="front-padding" v-drag v-loading="loading[0]" element-loading-text="拼命加载中..." element-loading-spinner="el-icon-loading" element-loading-background="#fff">
        <div class="front">
            <div class="tree-left bg-white">
                <div class="tit">部门名称</div>
                <div class="tree bj">
                    <el-scrollbar style="height: 100%;">
                        <el-tree :data="treeData" :props="defaultProps" node-key="id" :default-expanded-keys="dfExpKeys" ref="tree" :indent="10" accordion @node-click="nodeClick" :default-expand-all="false" :highlight-current="true"></el-tree>
                    </el-scrollbar>
                </div>
            </div>
            <div class="tree-right bg-white">
                <div class="widgets">
                    <el-input v-model.trim="searchText" placeholder="输入搜索内容" class="search__input" @keyup.enter.native="search"></el-input>
                    <el-button type="primary" @click="search">查询</el-button>
                    <div class="btn-group right">
                        <el-button type="info" @click="refresh">刷新</el-button>
                        <el-button type="primary" v-if="!systemId" disabled>新增</el-button>
                        <el-button type="primary" v-else @click="add">新增</el-button>
                        <el-button type="danger" v-if="multipleSelection.length <= 0" disabled>删除</el-button>
                        <el-button type="danger" v-else @click="del">删除</el-button>
                        <el-button type="danger" v-if="multipleSelection.length <= 0" disabled>禁用</el-button>
                        <el-button type="danger" v-else @click="disabedBtn(0, '禁用')">禁用</el-button>
                        <el-button type="success" v-if="multipleSelection.length <= 0" disabled>启用</el-button>
                        <el-button type="success" v-else @click="disabedBtn(1, '启用')">启用</el-button>
                        <el-button-group class="btn-other">
                            <el-button title="导出" v-if="multipleSelection.length <= 0" disabled>
                                <img src="../../../assets/images/export.png" alt="">
                            </el-button>
                            <el-button title="导出" v-else @click="exportExcel">
                                <img src="../../../assets/images/export.png" alt="">
                            </el-button>
                            <el-button title="导入">
                                <el-upload class="upload-demo" :action="$url + 'employee/importEmployee?systemId=' + systemId" :show-file-list="false" multiple style="display: inline-block;" :on-success="importExcelSuccess">
                                    <img src="../../../assets/images/import.png" alt="">
                                </el-upload>
                            </el-button>                        
                            <el-button title="打印">
                                <img src="../../../assets/images/print.png" alt="">
                            </el-button>
                            <el-button title="帮助">
                                <img src="../../../assets/images/help.png" alt="">
                            </el-button>
                        </el-button-group>
                    </div>
                </div>
                <div class="table top-bottom bj">
                    <el-scrollbar style="height: 100%;">
                        <el-table :data="tableData" border @selection-change="selectionChange" @row-contextmenu="rowContextmenu">
                            <el-table-column type="selection" align="center"></el-table-column>
                            <el-table-column type="index" label="序号" width="70" align="center"></el-table-column>
                            <el-table-column property="name" label="姓名" align="center"></el-table-column>
                            <el-table-column property="sex" label="性别" align="center">
                                <template slot-scope="scope">
                                    <span v-if="scope.row.sex == 0">女</span>
                                    <span v-if="scope.row.sex == 1">男</span>
                                </template>
                            </el-table-column>
                            <el-table-column property="deptName" label="部门" align="center"></el-table-column>
                            <el-table-column property="positionAux" label="职务" align="center"></el-table-column>
                            <el-table-column property="state" label="状态" align="center">
                                <template slot-scope="scope">
                                    <span style="color: green;" v-if="scope.row.state == 1">已启用</span>
                                    <span style="color: red;" v-else>已禁用</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" align="center">
                                <template slot-scope="scope">
                                    <el-button type="text" size="small" @click="viewData(scope.row.id)">查看</el-button>
                                    <el-button type="text" size="small" @click="update(scope.row)">修改</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-scrollbar>
                </div>
            </div>
        </div>
	</div>
</template>
<script>
export default {
	data() {
		return {
			searchText: '',
            loading: this.$store.state.empStore.loading,
			treeData: this.$store.state.empStore.treeData,
			tableData: this.$store.state.empStore.tableData,
			searchResult: this.$store.state.empStore.searchResult,           //查询
			defaultProps: {
                label: 'name',
                children: 'subDepartment',
                x: null,
                y: null
            },
			dfExpKeys: [],
			multipleSelection: [],
            selectRowId: []
		}
	},
	computed: {
		systemId() {
			return this.$store.state.systemId;
        }
	},
	watch: {
		treeData() {
			this.$nextTick(() => {
				let expandNodeId = this.$store.state.empStore.expandNodeId;
				this.dfExpKeys = [expandNodeId];
				this.$refs.tree.setCurrentKey(expandNodeId);
			});
        },
        searchText(newVal) {
            if(!newVal) {
                let expandNodeId = this.$store.state.empStore.expandNodeId;
                this.$store.dispatch('empStore/getEmployeeDataByDepartmentId', expandNodeId);
            }
        }
	},
	methods: {
        search() {
            if(this.searchText) {
                let data = this.searchResult,
                    newArr = [];
                data.forEach(item => {
                    if(item['name'].indexOf(this.searchText) > -1 || item['toSimplePinyin'].indexOf(this.searchText) > -1 || item['toNamePinyin'].indexOf(this.searchText) > -1) {
                        newArr.push(item);
                    }
                });
                this.$store.commit('empStore/updateTable', newArr);
            }
        },
		nodeClick(row) {
            if(this.searchText) this.searchText = '';
            this.$store.commit('empStore/updateExpandNodeId', row['id']);
            this.$store.dispatch('empStore/getEmployeeDataByDepartmentId', row['id']);
		},
		selectionChange(arr) {
			this.multipleSelection = arr;
            this.selectRowId = [];
            for(var i = 0; i < this.multipleSelection.length; i++) {
                this.selectRowId.push(this.multipleSelection[i]['id']);
            }
		},
		refresh() {
			const loading = this.$loading({
                lock: true,
                text: '数据刷新中...',
                spinner: 'el-icon-loading',
                background: '#fff'
            });
            setTimeout(() => {
                loading.close();
            }, 1000);
		},
		viewData(id) {			//查看
			this.$store.commit('empStore/updateRowId', id);
            this.$util.openLayerIframe({title: '职员-查看', width: '500px', height: '400px', url: this.$domain + '/#/basicData/employee/view'});
        },
		add() {
            this.$store.commit('empStore/updateRowId');
            this.$util.openLayerIframe({title: '职员-新增', width: '550px', height: '480px', url: this.$domain + '/#/basicData/employee/form'});
		},
		del() {
			this.$confirm('此操作将永久删除该文件, 是否继续？', '删除提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                var type = {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }
                
                //开始请求删除
                this.$http.post('employee/deleteEmployee', JSON.stringify(this.selectRowId), type).then(res => {
                    if(res.data.code == 20001) {
                        this.$message({message: '数据删除成功', type: 'success', duration: 1500});
                        setTimeout(() => {
                        	let expandNodeId = this.$store.state.empStore.expandNodeId;
                        	this.$store.dispatch('empStore/getEmployeeDataByDepartmentId', expandNodeId);			//刷新数据
                        }, 1000);
                    } else {
                        this.$message.error(res.data.msg || '删除失败');
                    }
                })
            }).catch(() => {
                this.$message({message: '已取消删除',type:'info'});          
            });
		},
		update(row) {
			this.$store.commit('empStore/updateRowId', row['id']);
            this.$util.openLayerIframe({title: '职员-修改', width: '500px', height: '400px', url: this.$domain + '/#/basicData/employee/form'});
		},
		disabedBtn(status, msg) {
			var type = {
                headers: {
                    'Content-type': 'application/json;charset=UTF-8'
                }
            }
            if(status == 0) {       //禁用
                for(var i = 0; i < this.multipleSelection.length; i++) {
                    if(this.multipleSelection[i]['state'] == status) {
                        this.$alert('禁用失败，其中包含已禁用选项，重新选择！', '禁用提示', {
                            confirmButtonText: '确定'
                        });
                        return false;
                    }
                }
            } else if(status == 1) {
                for(var i = 0; i < this.multipleSelection.length; i++) {
                    if(this.multipleSelection[i]['state'] == status) {
                        this.$alert('启用失败，其中包含已启动选项，重新选择！', '启动提示', {
                            confirmButtonText: '确定'
                        });
                        return false;
                    }
                }
            }
            this.$http.post('employee/startOrDisableEmployee?state=' + status, JSON.stringify(this.selectRowId), type).then(res => {
                if(res.data.code == 20001) {
                    this.$message({message: msg + '成功', type: 'success', duration: 1500});
                    setTimeout(() => {
                    	let expandNodeId = this.$store.state.empStore.expandNodeId;
                        this.$store.dispatch('empStore/getEmployeeDataByDepartmentId', expandNodeId);			//刷新数据
                        this.$store.dispatch('empStore/getSearch');
                    }, 1000);
                } else {
                    this.$message.error(this.data.msg || '禁用失败');
                }
            }).catch(err => {
                this.$message.error(err || '操作有误');
            });
		},
        disabedOneList(status, msg, row) {          //禁用、启用单条
            var type = {
                headers: {
                    'Content-type': 'application/json;charset=UTF-8'
                }
            }
            if(status == 0) {
                if(row['state'] == status) {
                    this.$message.error('禁用失败！当前数据已是禁用状态');
                    return false;
                }
            }
            if(status == 1) {
                if(row['state'] == status) {
                    this.$message.error('启用失败！当前数据已是启用状态');
                    return false;
                }
            }
            this.$http.post('employee/startOrDisableEmployee?state=' + status, JSON.stringify([row['id']]), type).then(res => {
                if(res.data.code == 20001) {
                    this.$message({message: msg + '成功', type: 'success', duration: 1500});
                    let expandNodeId = this.$store.state.empStore.expandNodeId;
                    setTimeout(() => {
                        this.$store.dispatch('empStore/getEmployeeDataByDepartmentId', expandNodeId);           //刷新数据
                    }, 500);
                }
            });
        },
		importExcelSuccess(res) {               //导入
            if(res.code === 20001) {
                this.$message({message: '导入成功', type: 'success', duration:1500});
                setTimeout(() => {
                    let expandNodeId = this.$store.state.empStore.expandNodeId;
                    this.$store.dispatch('empStore/getEmployeeDataByDepartmentId', expandNodeId);			//刷新数据
                }, 1000);
            }else{
                this.$message({message: res.msg, type: 'error',duration:2000});
            }
		},
		exportExcel() {         //导出
            if(this.multipleSelection.length > 0) {
                var idSting = this.selectRowId.join(',');           //将[1,2,3]格式转为 "1,2,3"
                this.$http.get('employee/exportEmployee',{params: { idList: idSting }}).then(res => {
                    this.$message({message: '导出成功', type: 'success', duration:1500});
                    window.location.href = this.$url + 'employee/exportEmployee?idList=' + idSting;          //导出时触发
                }).catch(err => {
                    this.$message.error(err);
                })
            } else {
                this.$message({message: '选择你要导出的数据', type: 'warning', duration: 1500});
            }
		}
	},
	mounted() {
        this.$store.commit('empStore/updateExpandNodeId');          //初始化展开节点
        this.$store.dispatch('empStore/getTreeData');
        this.$store.dispatch('empStore/getSearch');
    }
}
</script>